package com.example.linearlayoutdemo;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.linearlayoutdemo.network.auth.model.User;
import com.example.linearlayoutdemo.network.auth.viewmodel.LoginViewModel;
import com.example.linearlayoutdemo.network.auth.viewmodel.RegisterViewModel;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {


    // 声明控件
    private EditText etUsername;
    private EditText etPassword;
    private CheckBox cbAgree;
    private CheckBox cbAutologin;
    private Button btnLogin;
    private Button btnRegister;
    private ProgressBar progressBar;

    private Handler handler;

    // 邮箱验证的正则表达式
    private static final String EMAIL_REGEX = "^[a-zA-Z0-9_.]+@[a-zA-Z0-9]+(\\.[a-zA-Z0-9]+)+$";
    private Pattern pattern;

    // 定义一个常量，控制代码是否生效
    // DEBUG = 0 表示耗时操作在主线程执行；
    // DEBUG = 1 表示耗时操作在子线程，并调用Handler的post方法完成UI更新；
    // DEBUG = 2 表示耗时操作在子线程，并调用hander的sendMessage方法完成UI更新；
    // DEBUG = 3 表示耗时操作在子线程，在子线程中执行UI更新
    private static final int DEBUG = 2;

    private LoginViewModel loginViewModel;
    private RegisterViewModel registerViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("生命周期","onCreate:页面创建了");
        setContentView(R.layout.activity_main);

        // 初始化正则表达式模式
        pattern = Pattern.compile(EMAIL_REGEX);
        if(DEBUG == 2) {
            handler = new Handler(Looper.getMainLooper()) {
                @Override
                public void handleMessage(@NonNull Message msg) {
                    super.handleMessage(msg);
                    if(msg.what == 1) {
                        String result = (String) msg.obj;
                        //Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
                        progressBar.setVisibility(View.GONE);
                        if(TextUtils.equals(result,"登录失败") == false)
                        {
                            Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                            //
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra("email",etUsername.getText().toString().trim());
                            startActivity(intent);
                        } else {
                            Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
                        }


                    }
                }
            };
        } else {
            handler = new Handler(Looper.getMainLooper());
        }

        // 绑定控件
        initViews();
        etUsername.setText("eve.holt@reqres.in");
        etPassword.setText("cityslicka");
        cbAgree.setChecked(true);
        setUsernameTextChangeListener();
        setPasswordFocusChangeListener();
        // 设置按钮点击事件
        setButtonListeners();

        // 为CheckBox设置状态变化监听器
        cbAgree.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // isChecked 为当前状态：true表示勾选，false表示未勾选
                if (isChecked) {
                    // 勾选时的逻辑
                    Toast.makeText(MainActivity.this, "已同意用户协议", Toast.LENGTH_SHORT).show();
                    // 例如：可以在此处启用登录/注册按钮
                    // btnLogin.setEnabled(true);
                } else {
                    // 取消勾选时的逻辑
                    Toast.makeText(MainActivity.this, "请同意用户协议", Toast.LENGTH_SHORT).show();
                    // 例如：可以在此处禁用登录/注册按钮
                    // btnLogin.setEnabled(false);
                }
            }
        });

        // 检查是否可以自动登录
        if (loginViewModel.canAutoLogin()) {
            loginViewModel.autoLogin();
        }
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        cbAgree = findViewById(R.id.cb_agree);
        btnLogin = findViewById(R.id.btn_login);
        btnRegister = findViewById(R.id.btn_register);
        progressBar = findViewById(R.id.progress_loading);
        cbAutologin = findViewById(R.id.cb_autologin);
        loginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        registerViewModel = new ViewModelProvider(this).get(RegisterViewModel.class);
        setupObservers();
    }
    private void setupObservers() {
        // 观察加载状态
        loginViewModel.isLoading.observe(this, isLoading -> {
            if (isLoading) {
                progressBar.setVisibility(View.VISIBLE);
                btnLogin.setEnabled(false);
            } else {
                progressBar.setVisibility(View.GONE);
                btnLogin.setEnabled(true);
            }
        });

        // 观察错误信息
        loginViewModel.errorMessage.observe(this, errorMsg -> {
            if (errorMsg != null && !errorMsg.isEmpty()) {
                Toast.makeText(MainActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
            }
        });

        // 观察登录成功事件
        loginViewModel.loginSuccess.observe(this, isSuccess -> {
            if (isSuccess != null && isSuccess) {
                Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("email",etUsername.getText().toString().trim());
                startActivity(intent);
            }
        });

        // 观察加载状态
        registerViewModel.isLoading.observe(this, isLoading -> {
            if (isLoading) {
                progressBar.setVisibility(View.VISIBLE);
                btnRegister.setEnabled(false);
            } else {
                progressBar.setVisibility(View.GONE);
                btnRegister.setEnabled(true);
            }
        });

        // 观察错误信息
        registerViewModel.errorMessage.observe(this, errorMsg -> {
            if (errorMsg != null && !errorMsg.isEmpty()) {
                Toast.makeText(MainActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
            }
        });

        // 观察注册成功事件
        registerViewModel.registerSuccess.observe(this, isSuccess -> {
            if (isSuccess != null && isSuccess) {
                Toast.makeText(MainActivity.this, "注册成功，请登录", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void setButtonListeners() {
        // 登录按钮点击事件 匿名内部类
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleLogin();
            }
        });

        // 注册按钮点击事件
        btnRegister.setOnClickListener(v -> handleRegister());
    }
    private void setUsernameTextChangeListener() {
        etUsername.addTextChangedListener(new TextWatcher() {
            // 文本变化前调用
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 可用于记录变化前的状态
            }

            // 文本变化时调用
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // s为当前输入的文本
                String input = s.toString().trim();
                // 实时验证邮箱格式（输入过程中）
                if (!input.isEmpty() && !isValidEmail(input)) {
                    etUsername.setError("邮箱格式不正确");
                } else {
                    etUsername.setError(null); // 清除错误提示
                }
            }

            // 文本变化后调用
            @Override
            public void afterTextChanged(Editable s) {
                // 可用于处理变化后的逻辑，如输入完成后的操作
            }
        });

        // 内容变化监听的Lambda简写（Java 8+）
        /*
        etUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 实现同上
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });
        */
    }

    /**
     * 监听密码输入框的焦点变化
     */
    private void setPasswordFocusChangeListener() {
        etPassword.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                // 获得焦点时的操作
                Toast.makeText(MainActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                // 自动弹出软键盘（可选）
                /*
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.showSoftInput(etPassword, InputMethodManager.SHOW_IMPLICIT);
                */
            } else {
                // 失去焦点时的操作
                String password = etPassword.getText().toString().trim();
                if (password.length() > 0 && password.length() < 6) {
                    etPassword.setError("密码长度不能少于6位");
                } else {
                    etPassword.setError(null); // 清除错误提示
                }
                // 隐藏软键盘（可选）
                /*
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                */
            }
        });
    }
    /**
     * 处理登录逻辑
     */
    private void handleLogin() {
        // 获取输入内容
        String email = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        boolean isAgree = cbAgree.isChecked();

        // 验证输入
        if (!isValidEmail(email)) {
            Toast.makeText(this, "请输入有效的邮箱地址", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (password.length() < 6) {
            Toast.makeText(this, "密码长度不能少于6位", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!isAgree) {
            Toast.makeText(this, "请同意用户协议", Toast.LENGTH_SHORT).show();
            return;
        }

        // 所有验证通过，执行登录操作
//        Toast toast = Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT);
//        toast.show();
        // 这里可以添加实际登录逻辑，如网络请求等
//        progressBar.setVisibility(View.VISIBLE);
        if(DEBUG == 0) {
            try {
                Thread.sleep(3000); //耗时5s
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                Boolean isSuccess = new Random().nextBoolean();
                String result = isSuccess ? "登录成功" : "登录失败";
                Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.GONE);
            }
        } else if(DEBUG == 1) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(3000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        Boolean isSuccess = new Random().nextBoolean();
                        String result = isSuccess?"登录成功":"登录失败";
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this ,result,Toast.LENGTH_SHORT).show();
                                progressBar.setVisibility(View.GONE);
                            }
                        });
                    }
                }
            }).start();
        } else if(DEBUG == 2) {
            loginViewModel.login(email,password,cbAutologin.isChecked());
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            try {
//                                Thread.sleep(3000);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            } finally {
//                                Boolean isSuccess = new Random().nextBoolean();
//                                isSuccess = true;
//                                String result = isSuccess?"登录成功":"登录失败";
//                                Message msg = Message.obtain();
//                                msg.what = 1;
//                                msg.obj = result;
//                                handler.sendMessage(msg);
//                            }
//                        }
//                    }).start();
        } else if(DEBUG == 3) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(3000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        Boolean isSuccess = new Random().nextBoolean();
                        String result = isSuccess?"登录成功":"登录失败";
                        Toast.makeText(MainActivity.this ,result,Toast.LENGTH_SHORT).show();
                        progressBar.setVisibility(View.GONE);
                    }
                }
            }).start();
        }



    }

    /**
     * 处理注册逻辑
     */
    private void handleRegister() {
        // 获取输入内容
        String email = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        boolean isAgree = cbAgree.isChecked();

        // 验证输入（与登录类似，可根据实际需求调整）
        if (!isValidEmail(email)) {
            Toast.makeText(this, "请输入有效的邮箱地址", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (password.length() < 6) {
            Toast.makeText(this, "密码长度不能少于6位", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!isAgree) {
            Toast.makeText(this, "请同意用户协议", Toast.LENGTH_SHORT).show();
            return;
        }

//        // 所有验证通过，执行注册操作
//        Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
//        // 这里可以添加实际注册逻辑，如网络请求等

        registerViewModel.register(null, password, email);
    }

    /**
     * 验证邮箱格式
     * @param email 待验证的邮箱字符串
     * @return 符合格式返回true，否则返回false
     */
    private boolean isValidEmail(String email) {
        if (TextUtils.isEmpty(email)) {
            return false;
        }
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
//    打开 App → 依次执行 onCreate ()→onStart ()→onResume ()（页面从无到有，最终可操作）
//    按 Home 键返回桌面 → 执行 onPause ()→onStop ()（页面从可见到完全不可见）
//    从桌面再次打开 App → 执行 onRestart ()→onStart ()→onResume ()（页面从不可见恢复为可操作）
//    按返回键关闭 App → 执行 onPause ()→onStop ()→onDestroy ()（页面从可见到彻底消失）
    @Override
    protected void onStart() {
        super.onStart();
        Log.d("生命周期","onStart:页面开始可见了");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("生命周期","onResume:页面可以交互了");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("生命周期","onPause:页面部分遮挡或即将不可见了");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("生命周期","onStop:页面完全不可见了");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("生命周期","onRestart:页面即将重新可见");
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("生命周期","onDestroy:页面彻底消失");
    }
}